import React, { Component } from 'react'
import { WhiteSpace, Button, Toast } from 'antd-mobile'
import { Item, Icon, NavBar } from 'components'
import { post, msg } from '../../utils'
import './index.less'

export default class MobilePhoneLogin extends Component<any, any> {

    public autoFocusInst: any

    public yzmRef: any

    public accountRef: any

    public allTime = 60

    public state = {
        isGetVerification: false,
        account: '',
        reLabel: false,
        label: '发送验证码',
        verifyCode: '',
        verifyCodeError: false,
        loginBtnLoading: false,
        accountError: false,
    }
    private verifyMsg: string = ''
    private verificationPhoneTimer: number

    public render (): JSX.Element {
        const { loginBtnLoading, account, verifyCode, isGetVerification, accountError } = this.state
        return (
            <div className="mobileLogin">
                <div className="mobileLogin_NavBar">
                    <div className="mobileLogin_NavBar_conent">
                        <NavBar divider={false} title={<div className="mobileLogin_NavBar_title">手机号登录</div>}/>
                    </div>
                </div>
                <div className="mobileLogin_logo">
                    <img src={require('../../assets/logo.png')} />
                </div>
                <div className="mobileLogin_inputWrap">
                    <Item
                        className={`recoveredPsw_accountItem ${(accountError && account.length > 0) ? 'login_error_active' : ''}`}
                        title={this.accountInput()}
                    />
                    <WhiteSpace className="mobileLogin_whiteSpace"/>
                    {this.verificationCodeInput()}
                </div>
                <div className="mobileLogin_btnWrap">
                    <Button
                        className={`recoveredPsw_btnWrap_btn_default`}
                        loading={loginBtnLoading}
                        type="primary"
                        activeStyle={false}
                        onClick={this.handleLogin}
                        disabled={account.length === 0 || verifyCode.length !== 4 || !isGetVerification}
                    >
                        立即登录
                    </Button>
                </div>
            </div>
        )
    }
    private accountInput = () => {
        const { account } = this.state 
        return (
            <div className="recoveredPsw_accountItem_title">
                <div>
                    <Icon type="phone" className="recoveredPsw_accountItem_left_icon" />
                </div>
                <input
                    value={account}
                    placeholder="请输入手机号/用户名"
                    maxLength={11}
                    type="tel"
                    onChange={this.handleInputValue.bind(this, 'account')}
                />
                <div className="recoveredPsw_accountItem_right_icon">
                    {(account.length > 0)
                        ? <span className="mobileLogin_accountItem_right_erroricon">
                            <Icon type="error" onClick={this.handleClearValue.bind(this, 'account')} /></span>
                        : ''
                    }
                </div>
            </div>
        )
    }
    
    private verificationCodeInput = () => {
        const { verifyCode, label, reLabel, verifyCodeError, account } = this.state
        return (
            <div className={`recoveredPsw_verification_item`}>
                <div className={`recoveredPsw_verification_input ${(verifyCodeError) ? 'login_error_active' : ''}`}>
                    <Icon type="lock" className="recoveredPsw_verification_item_icon" />
                    <input
                        type="tel"
                        value={verifyCode}
                        placeholder="请输入短信验证码"
                        maxLength={4}
                        onChange={this.handleInputValue.bind(this, 'verifyCode')}
                    />
                </div>
                <Button className={`recoveredPsw_verification_btn ${(account.length === 11) ? 'recoveredPsw_verification_btn_active' : ''}`} disabled={reLabel} onClick={this.handleSendMsg}>{label}</Button>
            </div>
        )
    }

    private handleInputValue = (key: string, e: any) => {
        const val = e.target.value
        this.setState({
            [key]: val
        })
    }
    private handleClearValue = (key: string) => {
        this.setState({
            [key]: ''
        })
    }
    private handleSendMsg = () => {
        if (!this.handleCheckPhone()) {
            return
        }
        msg(`我们将发送验证码短信到这个手机号码： +86 ${this.state.account}`, '确认手机号码').then(() => {
                this.setState({
                    reLabel: true,
                    isGetVerification: true,
                })
                post('usersapi/sendSms', { phone: this.state.account, type: 2 }).then((data: any) => {
                    this.verifyMsg = `${data}`
                    this.setState({
                        reLabel: true,
                        label: '重新发送' + this.allTime + 'S',
                    })
                    const handleCountDown = () => {
                        this.allTime--
                        if (this.allTime === 0) {
                            this.setState({
                                label: '重新发送',
                                reLabel: false
                            })
                            clearInterval(this.verificationPhoneTimer)
                            this.allTime = 60
                        } else {
                            this.setState({
                                reLabel: true,
                                label: '重新发送' + this.allTime + 'S',
                            })
                        }

                    }
                    this.verificationPhoneTimer = window.setInterval(handleCountDown, 1000)
                }).catch((err: any) => {
                    this.setState({
                        reLabel: false
                    })
                })
            })
    }
    private handleCheckPhone = () => {
        const account = this.state.account
        const reg = /^[1][3,4,5,7,8][0-9]{9}$/
        if (account.length === 0) {
            Toast.info('请输入手机号码！', 1)
            return false
        } else {
            if (!reg.test(account)) {
                Toast.info('手机格式不正确！', 1, () => { this.showError('accountError') })
                return false
            }
        }
        this.showAccess('accountError')
        return true
    }
    private handleCheckVerification = () => {
        const verifyCode = this.state.verifyCode
        if (verifyCode.length !== 4) {
            Toast.info('请输入验证码！', 1)
            return false
        } else {
            if (verifyCode !== this.verifyMsg) {
                Toast.info('验证码不正确!', 1, () => { this.showError('verifyCodeError') })
                return false
            }
        }
        this.showAccess('verifyCodeError')
        return true
    }
    private showError(key: string) {
        this.setState({
            [key]: true
        })
    }
    private showAccess(key: string) {
        this.setState({
            [key]: false
        })
    }
    private handleLogin = () => {
        const { SET_USER_INFO, history } = this.props
        const { account } = this.state
        if (!this.handleCheckPhone() || !this.handleCheckVerification()) {
            return
        }
        this.setState({
            loginBtnLoading: true
        })
        post('usersapi/loginCode', {
            phone: account,
        }).then((data: any) => {
            this.setState({
                loginBtnLoading: false
            })
            SET_USER_INFO(data)
            history.go(-2)
        }).catch(() => {
            this.setState({
                loginBtnLoading: false
            })
        })
    }
    // private handleInputAccount = () => {
    //     const account = this.accountRef.value
    //     const { isGetVerification } = this.state
    //     if (account && account.length === 11) {
    //         if (this.handleCheckPhone() && !isGetVerification) {
    //             this.setState({
    //                 verificatonBtn: 'recoveredPsw_verification_btn recoveredPsw_verification_btn_active',
    //             })
    //         }
    //     } else {
    //         this.setState({
    //             verificatonBtn: 'recoveredPsw_verification_btn',
    //         })
    //     }
    //     this.handleAccountInputFocus()
    //     this.setLoginBtnDisable()
    // }
    
    // private handleInputverification = () => {
    //     this.handlePswInputFocus()
    //     this.setLoginBtnDisable()
    // }

    // private handlePswInputFocus = () => {
    //     if (this.yzmRef.value && this.yzmRef.value.length > 0) {
    //         this.showInputClear('accountFocus', false)
    //     }
    // }

    // private handleCheckPhone = () => {
    //     const account = this.accountRef.value
    //     const reg = /^[1][3,4,5,7,8][0-9]{9}$/
    //     if (account.length === 0) {
    //         Toast.info('请输入手机号码！', 1)
    //         this.showInputStatus('login', 'error')
    //         return false
    //     } else {
    //         if (!reg.test(account)) {
    //             Toast.info('手机格式不正确！', 1)
    //             this.showInputStatus('login', 'error')
    //             return false
    //         }
    //     }
    //     this.showInputStatus('login', 'success')
    //     return true
    // }
    // private handleCheckVerification = () => {
    //     const verificationCode = this.yzmRef.value
    //     const { isGetVerification } = this.state
    //     if (!isGetVerification) {
    //         Toast.info('请获取验证码！', 1)
    //         this.showInputStatus('verification', 'error')
    //         return false
    //     } else if (verificationCode && verificationCode.length !== 6) {
    //         Toast.info('验证码不正确！', 1)
    //         this.showInputStatus('verification', 'error')
    //         return false
    //     } 
    //     this.showInputStatus('verification', 'success')
    //     return true
    // }

    // private setLoginBtnDisable = () => {
    //     const account = this.accountRef.value
    //     const verification = this.yzmRef.value
    //     if (account && account.length > 0 && verification && verification.length > 0) {
    //         this.disableLoginBtn(false)
    //     } else {
    //         this.disableLoginBtn(true)
    //     }
    // }

    // private handleAccountInputFocus = () => {
    //     if (this.accountRef.value && this.accountRef.value.length > 0) {
    //         this.showInputClear('accountFocus', true)
    //     } else {
    //         this.showInputClear('accountFocus', false)
    //     }
    // }
    // private handleClearAccountInput = (ref: any) => {
    //     const { accoutInput } = this.state
    //     this.accountRef.value = ''
    //     this.showInputClear('accountFocus', false)
    //     this.disableLoginBtn(true)
    //     this.setState({
    //         accoutInput: {
    //             login: 'mobileLogin_accountItem',
    //             verification: accoutInput.verification
    //         }
    //     })
    //     this.accountRef.focus()
    // }
    // private disableLoginBtn = (status: boolean) => {
    //     let className =  (status) 
    //     ? 'mobileLogin_btnWrap_btn_default'
    //     :  'mobileLogin_btnWrap_btn_active'
    //     this.setState({
    //         mobileLoginBtn: className
    //     })
    // }
    // private showInputClear = (type: string, isShow: boolean) => {
    //     let temp = {}
    //     temp[type] = isShow
    //     this.setState(temp)
    // }
    // private showInputStatus = (type: string, status: string) => {
    //     const temp = cloneDeep(this.state.accoutInput)
    //     if (type !== 'verification') {
    //         if (status === 'success') {
    //             temp[type] = 'mobileLogin_accountItem'
    //         } else if (status === 'error') {
    //             temp[type] = 'mobileLogin_accountItem login_error_active'
    //         }
    //     } else {
    //         if (status === 'success') {
    //             temp[type] = 'mobileLogin_verification_input'
    //         } else if (status === 'error') {
    //             temp[type] = 'mobileLogin_verification_input login_error_active'
    //         }
    //     }
    //     this.setState({
    //         accoutInput: temp
    //     })
    // }
}